import MyCos from '@/utils/cosUpload'

/**
 * [uploadFile 上传文件]
 * @param  {[type]} that            [cos-v5 obj]
 * @param  {[type]} remoteFilePath [description]
 * @param  {[type]} filePath       [description]
 * @return {[type]}                [description]
 */
function uploadFile(file) {
  // 上传文件
  return new Promise(function(resolve, reject) {
    MyCos.init.putObject({
      Bucket: MyCos.config.Bucket, // 存储桶名称
      Region: MyCos.config.Region, // 地区
      Key: 'pic/' + file.name, // 图片名称
      StorageClass: 'STANDARD',
      Body: file.raw // 上传文件对象
    }, function(err, data) {
      return err ? reject(err) : resolve(data)
    })
  })
}

/**
 * [traverseUpload 递归上传]
 * @param  {[type]} files     [description]
 * @param  {[type]} countConf [description]
 * @return {[type]}           [description]
 */
async function traverseUpload(files, countConf) {
  if (files.length <= 0) { // 成功
    return Promise.resolve(countConf)
  }

  var file = files.shift()

  function catchError(error) {
    countConf.fail++
    countConf.failList.push(file)
    return Promise.reject(error)
  }
  function uploaded(data) {
    countConf.success++
    countConf.successList.push({
      sourceUrl: data.Location
    })
  }
  return await uploadFile(file)
    .then(uploaded, catchError)
    .then(function() {
      // that.progress(countConf)
      return traverseUpload(files, countConf)
    })
}
/**
 * [upload 文件上传接口]
 * @param  {[type]} files    [description]
 * @return {[type]}          [description]
 */
async function cosUploadTraverse(files) {
  var countConf = { total: files.length || 0, success: 0, fail: 0, successList: [], failList: [] }
  await traverseUpload(files, countConf)

  return countConf
}

export default cosUploadTraverse
